$(function () {
    var layer = layui.layer;
    var form = layui.form;
    initArtList();
    function initArtList() {
        $.ajax({
            method: 'GET',
            url: '/my/article/cates',
            success: function (res) {
                // console.log(res);
                if (res.status !== 0) {
                    return layer.msg(res.message);
                }
                var htmlStr = template('tpl-table', res.data);
                $('tbody').html(htmlStr);
            }
        });
    }

    var indexAdd = null;
    $('#btnAddCate').on('click', function () {
        indexAdd = layer.open({
            type: 1,
            title: '添加类别',
            area: ['500px', '250px'],
            content: $('#dialog-add').html(),
        });
    });

    $('body').on('submit', '#form-add', function (e) {
        e.preventDefault();
        $.ajax({
            method: 'POST',
            url: '/my/article/addcates',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) {
                    $('#form-add').reset();
                    return layer.msg(res.message);
                }
                initArtList();
                layer.close(indexAdd);
            }
        });
    });

    var indexEdit = null;
    $('body').on('click', '.btn-edit', function () {
        indexEdit = layer.open({
            type: 1,
            title: '编辑类别',
            area: ['500px', '250px'],
            content: $('#dialog-eidt').html(),
        });

        var id = $(this).data('id');
        $.ajax({
            method: 'GET',
            url: '/my/article/cates/' + id,
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg(res.message);
                }
                form.val('form-edit', res.data);
            }
        });
    });

    $('body').on('submit', '#form-edit', function (e) {
        e.preventDefault();

        $.ajax({
            method: 'POST',
            url: '/my/article/updatecate',
            data: $(this).serialize(),
            success: function (res) {
                if (res.status !== 0) {
                    return layer.msg(res.message);
                }
                layer.close(indexEdit);
                initArtList();
            }
        });
    });

    $('body').on('click', '.btn-del', function () {
        var id = $(this).data('id');
        layer.confirm('确认删除?', { icon: 3, title: '提示' }, function (index) {
            $.ajax({
                method: 'GET',
                url: '/my/article/deletecate/' + id,
                success: function (res) {
                    if (res.status !== 0) {
                        return layer.msg(res.message);
                    }
                    layer.msg(res.message);
                    initArtList();
                }
            });
            layer.close(index);
        });
    });
});